<template>
  <div class="container-fluid">
    <!-- 导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="d-flex align-items-center justify-content-between w-100">
        <div>
          <h1>停车场管理系统</h1>
        </div>
        <div class="d-flex items-center ml-auto" style="margin-left: auto;">
          <span id="usernameDisplay" class="mr-4">管理员</span>
          <router-link to="/" class="btn btn-light mr-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light">退出</button>
        </div>
      </div>
    </header>
    
    <div class="container-fluid h-100">
      <div class="login-card row h-100 justify-content-center align-items-center">
        <div class="col-md-4">
          <div class="card">
            <div class="card-body">
              <form @submit.prevent="login">
                <div class="form-group">
                  <label for="username">用户名</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="username" 
                    placeholder="请输入用户名" 
                    v-model="username"
                  >
                </div>
                <div class="form-group">
                  <label for="password">密码</label>
                  <input 
                    type="password" 
                    class="form-control" 
                    id="password" 
                    placeholder="请输入密码" 
                    v-model="password"
                  >
                </div>
                <div class="form-group form-check">
                  <input 
                    type="checkbox" 
                    class="form-check-input" 
                    id="remember" 
                    v-model="remember"
                  >
                  <label class="form-check-label" for="remember">记住我</label>
                </div>
                <button type="submit" class="btn btn-primary btn-block">登录</button>
              </form>
              <div class="mt-3 text-center">
                <router-link to="/" class="text-primary">返回首页</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 消息提示 -->
    <div 
      v-if="message" 
      :class="['alert', messageType === 'error' ? 'alert-danger' : messageType === 'success' ? 'alert-success' : 'alert-info', 'alert-custom fade-in']"
      role="alert"
    >
      {{ message }}
    </div>
  </div>
</template>

<script>
import axios from '../utils/axios';

export default {
  name: 'LoginView',
  data() {
    return {
      username: '',
      password: '',
      remember: false,
      message: '',
      messageType: ''
    }
  },
  mounted() {
    this.checkRememberedPassword()
  },
  methods: {
    checkRememberedPassword() {
      const rememberedUser = localStorage.getItem('rememberedUser')
      if (rememberedUser) {
        const user = JSON.parse(rememberedUser)
        this.username = user.username
        this.password = user.password
        this.remember = true
      }
    },
    
    async login() {
      // 简单验证
      if (!this.validateUsername(this.username)) {
        this.showMessage('请输入有效的用户名', 'error')
        return
      }

      if (!this.validatePassword(this.password)) {
        this.showMessage('请输入有效的密码（至少6位）', 'error')
        return
      }

      try {
        // 发送登录请求到2509端口的后端服务
        const response = await axios.post('/api/login', {
          username: this.username,
          password: this.password
        })
        
        if (response.success) {
          this.handleLoginSuccess()
        } else {
          this.showMessage(response.message || '用户名或密码错误', 'error')
        }
      } catch (error) {
        console.error('Login error:', error)
        // 如果后端服务不可用，使用模拟登录
        this.handleMockLogin()
      }
    },
    
    handleLoginSuccess() {
      // 处理记住密码
      if (this.remember) {
        localStorage.setItem('rememberedUser', JSON.stringify({
          username: this.username,
          password: this.password
        }))
      } else {
        localStorage.removeItem('rememberedUser')
      }

      // 模拟存储登录状态
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('username', this.username)

      this.showMessage('登录成功，正在跳转到首页...', 'success')

      // 跳转到首页
      setTimeout(() => {
        this.$router.push('/')
      }, 1500)
    },
    
    handleMockLogin() {
      // 模拟登录逻辑 - 使用预设的用户名密码
      const validUsers = {
        'admin': 'password123',
        'user1': 'user12345',
        'test': 'test123'
      }
      
      if (validUsers[this.username] === this.password) {
        // 显示使用模拟登录的提示
        this.showMessage('使用模拟登录成功，正在跳转到首页...', 'success')
        
        // 存储登录状态
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('username', this.username)
        
        // 处理记住密码
        if (this.remember) {
          localStorage.setItem('rememberedUser', JSON.stringify({
            username: this.username,
            password: this.password
          }))
        }
        
        // 跳转到首页
        setTimeout(() => {
          this.$router.push('/')
        }, 1500)
      } else {
        this.showMessage('用户名或密码错误，请使用模拟账号（admin/password123 或 user1/user12345）', 'error')
      }
    },
    
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    
    validateUsername(username) {
      return username.length >= 2 && username.length <= 20
    },
    
    validatePassword(password) {
      return password.length >= 6
    },
    
    showMessage(message, type = 'info') {
      this.message = message
      this.messageType = type
      
      // 3秒后移除消息
      setTimeout(() => {
        this.message = ''
      }, 3000)
    },
    
    // 模拟请求函数
    request(url, method = 'GET') {
      // 模拟响应
      return new Promise((resolve) => {
        // 模拟网络延迟
        setTimeout(() => {
          // 简单模拟成功登录
          if (url === '/api/login' && method === 'POST' && this.username && this.password) {
            resolve({
              success: true,
              message: '登录成功'
            })
          } else {
            resolve({
              success: false,
              message: '请求失败'
            })
          }
        }, 500)
      })
    }
  }
}
</script>

<style >
/* 这里可以添加组件特定的样式 */

</style>